package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/9/19  16:33
 *  @描述       ${TODO}
 *
 *  where:
 *          SmallBEJGoodsListActivity:商品分类
 *          SmallBGoodsListActivity  :商品列表
 *
 */


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.SmallBGoodsListAdapter;
import com.yanq.liancar.bean.BShopGoodsListBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class SmallBSearchActivity extends BaseToolbarActivity {

    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.goodslistview)
    RecyclerView goodslistview;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.et_search)
    EditText etSearch;
    private List<BShopGoodsListBean.DataBean.ListBean> goodsListBeans = new ArrayList<>();
    private SmallBGoodsListAdapter adapter;
    private int page = 1;
    private boolean isClear = true;
    private int pages,Bid,Sid,type;
    private String where;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_b_search);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("商品搜索");

        where=getIntent().getExtras().getString("where");
        if ("SmallBEJGoodsListActivity".equals(where)){
            Bid=getIntent().getExtras().getInt("Bid");
            Sid=getIntent().getExtras().getInt("Sid");
        }else {
            type=getIntent().getExtras().getInt("type");
        }

        initRecyclerView();
        refreshListener();

        findViewById(R.id.tv_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                if (isNull(etSearch.getText().toString().trim())){
                    if ("SmallBEJGoodsListActivity".equals(where)){
                        initOkgo1();
                    }else {
                        initOkgo();
                    }
                }
            }
        });
    }

    private void initRecyclerView() {
        goodslistview.setNestedScrollingEnabled(false);
        goodslistview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SmallBGoodsListAdapter(R.layout.item_small_b_goodslist, goodsListBeans);
        goodslistview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("goodsID", goodsListBeans.get(position).getGoodsid());
                RxActivityTool.skipActivity(mContext, SmallBGoodsDetailsActivity.class, bundle);
            }
        });
    }

    private void refreshListener() {
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                isClear = true;
                //网络请求
                initOkgo();
                refreshLayout.finishRefresh();
            }
        });

        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isClear = false;
                page++;
                //网络请求
                LogUtils.e("dadasdada", pages + "=====" + page);
                if (pages >= page) {
                    initOkgo();
                }
                refreshLayout.finishLoadMore();
            }
        });
    }

    private void initOkgo() {
        OkGo.<String>post(Config.s + "llc/api/searchGoods")
                .tag(this)
                .params("name",etSearch.getText().toString().trim())
                .params("pageNum", page)
                .params("pageSize", 7)
                .params("goods_classify", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BShopGoodsListBean selectClassifyBean = gson.fromJson(response.body(), BShopGoodsListBean.class);
                        if (selectClassifyBean.isIsSuccess()) {
                            pages = selectClassifyBean.getData().getPages();
                            if (isClear) {
                                goodsListBeans.clear();
                            }
                            goodsListBeans.addAll(selectClassifyBean.getData().getList());
                            adapter.setNewData(goodsListBeans);
                        } else {
                            RxToast.error(selectClassifyBean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    private void initOkgo1() {
        OkGo.<String>post(Config.s + "llc/api/searchSmallGoods")
                .tag(this)
                .params("name",etSearch.getText().toString().trim())
                .params("pageNum", page)
                .params("pageSize", 7)
                .params("big_classifyid", Bid)
                .params("small_classifyid", Sid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BShopGoodsListBean selectClassifyBean = gson.fromJson(response.body(), BShopGoodsListBean.class);
                        if (selectClassifyBean.isIsSuccess()) {
                            pages = selectClassifyBean.getData().getPages();
                            if (isClear) {
                                goodsListBeans.clear();
                            }
                            goodsListBeans.addAll(selectClassifyBean.getData().getList());
                            adapter.setNewData(goodsListBeans);
                        } else {
                            RxToast.error(selectClassifyBean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    private boolean isNull( String str){
        if (TextUtils.isEmpty(str)){
            RxToast.error("请输入搜索内容");
            return false;
        }
        return true;
    }
}
